<script setup>
import Cell from '@/components/cell/index.vue'
import CellItem from '@/components/cell-item/index.vue'
import IconSimple from '@/components/icon-simple/index.vue'
import {computed, ref} from 'vue'

const props = defineProps({
  modelValue: [String, String],
  options: {
    type: Object,
    default: () => ({
      label: 'label',
      value: 'value'
    })
  },
  data: {
    type: Array,
    default: () => []
  },
  placeholder: String
})

const emit = defineEmits(['update:modelValue', 'change'])

const trigger = ref(false)
const val = ref(props.modelValue)
const label = computed(() => {
  const findResult = props.data.find(item => item[props.options.value] === val.value)
  if (findResult) return findResult[props.options.label]
  return ''
})
const placeholder = computed(() => label.value ? '' : props.placeholder)

const selectClick = (item, index) => {
  val.value = item[props.options.value]
  emit('update:modelValue', val.value)
  emit('change', {detail: item, index})
}
</script>

<template>
  <view class="selector-x-container">
    <view class="selector-x-mask" v-if="trigger" @click="trigger = !trigger"></view>
    <cell class="selector-bar-container selector-bar-container-transparent">
      <cell-item :label="label" :placeholder="placeholder" />
    </cell>
    <cell class="selector-bar-container">
      <cell-item text-align="left" :label="label" @click.stop.prevent="trigger = !trigger" :placeholder="placeholder">
        <template #rightIcon>
          <icon-simple class="icon-simple" :class="{ 'selector-bar-selected': trigger }" name="retract" />
        </template>
      </cell-item>
    </cell>
    <cell class="selector-options" v-if="trigger">
      <cell-item v-for="(item,index) of props.data" :label="item[props.options.label]" :key="index" :right-icon="item[props.options.value] === val ? 'yes' : 'no'" @click.stop.prevent="selectClick(item, index)" />
    </cell>
  </view>
</template>

<style scoped lang="scss">
.selector-x-container {
  position: relative;
}
.selector-x-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(#000, .4);
}
.selector-bar-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 11;
}
.selector-options {
  position: absolute;
  top: 140rpx;
  left: 0;
  right: 0;
  z-index: 12;
}
.selector-bar-container-transparent {
  position: static;
  opacity: 0;
}

.icon-simple {
  display: block;
  transition: all .3s;
  transform: rotate(180deg);
}

.selector-bar-selected {
  transform: rotate(0deg);
}
</style>
